package cn.hhz.ivos.vehicle.service.impl;

import cn.hhz.ivos.vehicle.mapper.VehicleMapper;
import cn.hhz.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.hhz.ivos.vehicle.pojo.dto.VehicleSaveParam;
import cn.hhz.ivos.vehicle.pojo.entity.Vehicle;
import cn.hhz.ivos.vehicle.pojo.vo.VehicleVO;
import cn.hhz.ivos.vehicle.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class VehicleServicelmpl implements VehicleService {
    @Autowired
    VehicleMapper vehicleMapper;

    @Override
    public List<VehicleVO> selectVehicle(VehicleQuery vehicleQuery) {
        log.debug("查询车辆业务：vehicleQuery={}", vehicleQuery);
        List<VehicleVO> list = vehicleMapper.selectVehicle(vehicleQuery);
        return list;
    }

    @Override
    public void saveVehicle(VehicleSaveParam vehicleSaveParam) {
        log.debug("保存车辆信息业务：vehicleSaveParam={}", vehicleSaveParam);
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleSaveParam, vehicle);
        if (vehicle.getId() == null) {
            vehicle.setCreateTime(new Date());
            vehicle.setStatus("1");
            vehicleMapper.insert(vehicle);
        } else {
            vehicle.setUpdateTime(new Date());
            vehicleMapper.update(vehicle);
        }
    }

    @Override
    public void deleteVehicle(Long id) {
        log.debug("删除车辆信息业务：id={}", id);
        vehicleMapper.delete(id);
    }

    @Override
    public void unbindVehicle(Long vehicleId) {
        log.debug("解绑车辆id={}",vehicleId);
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceBindStatus("0");
        vehicle.setGeofenceId(null);
        vehicle.setUpdateTime(new Date());
        /*之前的更新SQL要求围栏编号不能为null才会更新围栏编号
         * 但此处由于业务=>将车辆与围栏解除绑定关系
         * 需要将围栏编号置为null,所以需要重写一个mapper层的方法*/
        vehicleMapper.updateunbind(vehicle);
    }

    @Override
    public void bindVehicle(Long genofenceID, Long vehicleID) {
        log.debug("绑定车辆业务id={}，绑定电子围栏Id={}",vehicleID,genofenceID);
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleID);
        vehicle.setGeofenceBindStatus("1");
        vehicle.setGeofenceId(genofenceID);
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }
}
